include ../../Makefile.config
export PATH := $(PATH):$(NDLUA_TOP)/extlibs/luajitlib/buildbin

all: luajit-src-extract LuaJIT-2.0.0-beta10 patch buildbin ../dist
	@becho "Building LuaJIT library..."
	make -C LuaJIT-2.0.0-beta10 HOST_CC="gcc -m32" CFLAGS="-DLJ_TARGET_NSPIRE" CROSS=nspire- BUILDMODE=static TARGET_SYS=nspire
	@becho "Installing LuaJIT library to the ndLua source tree..."
	make -C LuaJIT-2.0.0-beta10 install PREFIX=$(NDLUA_TOP)/extlibs/dist

../dist:
	@becho "Distribution directory doesn't exist. Creating it now."
	make -C .. dirprep

luajit-src-extract:
	@becho "Extracting LuaJIT source..."
	if [ -d LuaJIT-2.0.0-beta10 ]; then rm -rf LuaJIT-2.0.0-beta10; fi
	tar -xvf LuaJIT-2.0.0-beta10.tar.gz && touch luajit-src-extract

# If we run this target, that means something made the nspireio-2.0
# source directory disappear! We need to fix that.
LuaJIT-2.0.0-beta10:
	@becho "Uh oh... the LuaJIT source directory disappeared! Attempting to recover..."
	rm -f luajit-src-extract
	make luajit-src-extract
	@becho "Successfully recovered from missing LuaJIT source directory."

patch: LuaJIT-2.0.0-beta10
	@becho "Applying patch 'luajit-2.0b10-nspire-support.patch'..."
	cd LuaJIT-2.0.0-beta10 && patch -Ns -p0 < ../luajit-2.0b10-nspire-support.patch && cd .. && touch patch

rmpatch: patch
	@becho "Reversing patch 'luajit-2.0b10-nspire-support.patch'..."
	cd LuaJIT-2.0.0-beta10 && patch -Rs -p0 < ../luajit-2.0b10-nspire-support.patch && cd .. && rm patch

buildbin:
	@becho "Creating link for nspire-* tools..."
	mkdir -p buildbin
	ln -s `which arm-none-eabi-ar` buildbin/nspire-ar
	ln -s `which arm-none-eabi-strip` buildbin/nspire-strip

clean:
	@becho "Cleaning up LuaJIT source tree..."
	make -C LuaJIT-2.0.0-beta10 clean

distclean-init:
	@becho "Cleaning up all of LuaJIT source tree..."

distclean: distclean-init rmpatch
	make -C LuaJIT-2.0.0-beta10 clean
	rm -rf LuaJIT-2.0.0-beta10 luajit-src-extract patch buildbin

